package com.cc.dlnalib;

import android.util.Log;

import org.cybergarage.upnp.Device;

public class StateMonitor {
    private static final String TAG = "StateMonitor";
    private Thread thread;

    private MultiPointController controller;

    private String currentState = DLNAControllerKt.STATE_STOPPED;

    public StateMonitor(MultiPointController controller) {
        this.controller = controller;
    }

    public void start(Device device) {
        Log.i(TAG, "start");
        stop();
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!thread.isInterrupted()) {
                    String state = controller.getTransportState(device);
                    if (state != null && !state.equals(currentState) && callBack != null) {
                        currentState = state;
                        if (!thread.isInterrupted()) {
                            callBack.onStateChanged(state);
                        }
                    }
                    try {
                        synchronized (this) {
                            wait(1000);
                        }
                    } catch (InterruptedException e) {
                        Log.i(TAG, "run: thread interrupted.");
                    }
                }
            }
        });
        thread.start();
    }

    public void stop() {
        if (thread != null) {
            Log.i(TAG, "try stop.");
            thread.interrupt();
        }
    }

    private StateCallBack callBack;

    public void setCallBack(StateCallBack callBack) {
        this.callBack = callBack;
    }

    public interface StateCallBack {
        void onStateChanged(String state);
    }
}
